package app.dev.ems.manager.impl;

import java.util.EnumMap;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import app.dev.ems.data.dao.ISettingsDao;
import app.dev.ems.data.element.SettingType;
import app.dev.ems.data.model.impl.BaseSettings;
import app.dev.ems.data.model.impl.ProfileSettings;
import app.dev.ems.data.model.impl.Settings;
import app.dev.ems.manager.ISettingsManager;

public class SettingsManagerImpl extends BaseManagerImpl<Settings> implements ISettingsManager {

	private ISettingsDao settingsDao;
	private static EnumMap<SettingType, BaseSettings> settingMap;
	
	static {
		settingMap = new EnumMap<SettingType, BaseSettings>(SettingType.class);
		settingMap.put(SettingType.PROFILE, new ProfileSettings());
	}

	public void setSettingsDao(ISettingsDao settingsDao) {
		super.setEntityDao(settingsDao);
		this.settingsDao = settingsDao;
	}

	public Settings createNewProfileSettings() {
		return createNewSettings(SettingType.PROFILE);
	}
	
	public Settings getProfileSettings() {
		return getSettings(SettingType.PROFILE);
	}
	
	@Transactional(readOnly = true)
	private Settings getSettings(SettingType settingType) {
		Criterion criterion = Restrictions.eq("settingType", settingType);
		List<Settings> settings = settingsDao.get(criterion);
		if(settings != null && settings.size() > 0) {
			return settings.get(0);
		}
		return null;
	}
	
	private Settings createNewSettings(SettingType settingType) {		
		Settings settings = new Settings();
		BaseSettings baseSettings = settingMap.get(settingType);
		baseSettings.initialize();
		settings.setSettings(baseSettings);
		settings.setSettingType(settingType);
		return settings;
	}
}
